<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
import { computed, ref } from 'vue'

import { useLogin } from './composables/useLogin'
import type { FormRule } from '@/types/components-tool'

import enUS from './locales/en-US.json' with { type: 'json' }
import zhCN from './locales/zh-CN.json' with { type: 'json' }

const passwordRemember = ref<boolean>(true)
const autocompleteState = computed(() => (passwordRemember.value ? 'on' : 'off'))

const { t } = useI18n<[typeof zhCN], Locales>({ messages: { 'en-US': enUS, 'zh-CN': zhCN } })
const { formState, isPending, handleLogin } = useLogin()

const loginFormRules: FormRule<typeof formState> = {
  username: [
    { required: true, message: t('card.form.username.placeholder') },
    { length: 8, message: t('card.form.username.length', { length: 8 }) }
  ],
  password: [
    { required: true, message: t('card.form.password.placeholder') },
    { minLength: 8, message: t('card.form.password.minLength', { length: 7 }) },
    { maxLength: 64, message: t('card.form.password.maxLength', { length: 65 }) }
  ]
}
</script>

<template>
  <div class="card">
    <header>
      <h3 class="text-center mt-0 text-arco-2">{{ t('card.title') }}</h3>
    </header>
    <a-divider orientation="center">
      <span class="text-arco-2">{{ t('card.subtitle') }}</span>
    </a-divider>
    <a-form
      @submit-success="handleLogin"
      :model="formState"
      layout="vertical"
      :rules="loginFormRules"
    >
      <a-form-item field="username" hide-asterisk hide-label>
        <a-input
          data-e2e="input-username"
          v-model="formState.username"
          :placeholder="t('card.form.username.placeholder')"
          :autocomplete="autocompleteState"
        >
          <template #prefix><i i-fluent-person-12-regular /></template>
        </a-input>
      </a-form-item>

      <a-form-item field="password" hide-asterisk hide-label>
        <a-input-password
          data-e2e="input-password"
          v-model="formState.password"
          :placeholder="t('card.form.password.placeholder')"
          :autocomplete="autocompleteState"
        >
          <template #prefix><i i-uil-lock-alt /></template>
        </a-input-password>
      </a-form-item>

      <a-form-item no-style field="password">
        <a-checkbox v-model="passwordRemember">{{ t('card.form.remember') }}</a-checkbox>
      </a-form-item>

      <a-form-item no-style>
        <a-button
          data-e2e="button-login"
          :loading="isPending"
          :disabled="isPending"
          html-type="submit"
          type="primary"
          class="mt-4"
          long
        >
          {{ t('card.button') }}
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
